import { createRouter, createWebHashHistory } from "vue-router";

const routes = [
	{
	   path: '/login',
	   name: 'login',
	   component: () => import('../views/login.vue'),
	   meta: {
		   title: '登录'
	   }
	 },
	{
	   path: '/index',
	   name: 'index',
	   component: () => import('../views/index.vue'),
	   children: [
		   {
		     path: '/sys',
			 children: [
				 {
				   path: '/sys/user',
				   name: 'sysUser',
				   component: () => import('../views/sys/user.vue'),
				   meta: {
				   		   title: '用户管理'
				   }
				 },
				 {
				    path: '/sys/menu',
				    name: 'sysMenu',
				    component: () => import('../views/sys/menu.vue'),
					meta: {
							title: '菜单管理'
					}
				  },
				  {
				     path: '/sys/role',
				     name: 'sysRole',
				     component: () => import('../views/sys/role.vue'),
				  					meta: {
				  							title: '角色管理'
				  					}
				   }
			 ]
		   },
		   {
			   path: '/goods',
			   children: [
			   {
				  path: '/goods/type',
				  name: 'goodsType',
				  component: () => import('../views/goods/goodsType.vue'),
				  meta: {
				  		   title: '商品类型管理'
				  }
				},
				{
				   path: '/goods',
				   name: 'goods',
				   component: () => import('../views/goods/goods.vue'),
				   meta: {
				   		   title: '商品管理'
				   }
				 }
			 ]
		   }
	   ]
	 }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes 
})

// 路由拦截器
router.beforeEach((to, from, next) => {
	if (to.meta.title) { // 判断是否有标题
		document.title = to.meta.title;
	  } else {
		  document.title = '服装后台管理系统';
	  }
	const token = sessionStorage.getItem('token');
	// console.log(to)
	if (to.name === 'login' || to.name === 'register') {
		next();
	} else if (token) {
	  // 如果已经登录
	  next();
	} else {
	  // 否则跳转到登录页
	  next({
		path: '/login',
		query: { redirect: to.fullPath } // 将跳转的路由 path 作为参数，登录成功后跳转到该路由
	  });
	}
});

export default router